package cn.amoqi.springboot.mybatisplus.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {
    private static String packages = "cn.amoqi.springboot.mybatisplus";
    private static String superEntityClass = packages + ".common.BaseEntity";
    private static String superControllerClass = packages + ".common.BaseController";
    private static String author = "lium";
    //SQLSERVER
    //private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=RomensManage";
    //private static String DriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static String url = "jdbc:mysql://localhost:3306/springboot-mybatis-plus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=CTT";
    private static String DriverName = "com.mysql.cj.jdbc.Driver";
    private static String username = "root";
    private static String password = "123456";
    private static Boolean enableSwagger = true;
    private static Boolean fileOverride = true;
    //如果要配置用户自定义模版
    //自定义模版文件夹位置
    private static String myTempPackage = "/myTemp";
    private static Boolean useCustomTemp = true;

    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (ipt!=null && ipt.length()>=0) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");

        String pathStr = CodeGenerator.class.getClassLoader().getResource("").getPath();
        if(pathStr.startsWith("/")){
            pathStr = pathStr.substring(1);
        }
        int index = pathStr.indexOf("/target");
        if(index>0){
            pathStr = pathStr.substring(0,index);
        }

        String finalPathStr = pathStr;

        gc.setOutputDir(finalPathStr + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(enableSwagger);
        //开启覆盖
        gc.setServiceName("%sService");
        gc.setFileOverride(fileOverride);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        // dsc.setSchemaName("public");
        dsc.setDriverName(DriverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(packages);//packages = "cn.amoqi.mybaitsplus";
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出

        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return finalPathStr + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        if(useCustomTemp){
            templateConfig.setServiceImpl(myTempPackage+"/serviceImpl.java");
            templateConfig.setController(myTempPackage+"/controller.java");
            templateConfig.setService(myTempPackage+"/service.java");
        }
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass(null);
        //strategy.setSuperEntityColumns("id");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //strategy.setSuperControllerClass(superControllerClass);
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        if(useCustomTemp){
            MyFreemarkerTemplateEngine myFreemarkerTemplateEngine = new MyFreemarkerTemplateEngine();
            myFreemarkerTemplateEngine.setBasicPackage(packages);
            myFreemarkerTemplateEngine.setAddInTemplate(myTempPackage+"/addIn.java");
            myFreemarkerTemplateEngine.setEditInTemplate(myTempPackage+"/editIn.java");
            mpg.setTemplateEngine(myFreemarkerTemplateEngine);
        }else{
            FreemarkerTemplateEngine freemarkerTemplateEngine = new FreemarkerTemplateEngine();
            mpg.setTemplateEngine(freemarkerTemplateEngine);
        }
        mpg.execute();
    }

}


